<?php

namespace app\models;

use Yii;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "project".
 *
 * @property int $id
 * @property string $name 客户姓名
 * @property int $sex 客户性别，【1：男，2：女，3：保密】
 * @property string $phone 联系电话
 * @property string $other_phone 其它电话
 * @property string $company 公司名称
 * @property int $created_user_id 创建用户ID
 * @property int $updated_user_id 更新用户ID
 * @property int $created_at
 * @property int $updated_at
 */
class Project extends \yii\db\ActiveRecord
{

    public static $sex_info = [1=>'男',2=>'女',3=>'保密'];
    public $content;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'project';
    }

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'created_user_id',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_user_id',
                ],
                'value' => function($event){
                    return Yii::$app->user->identity->id;
                }
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['name','required','on'=>['create','edit']],
            ['name','string', 'max' => 200,'on'=>['create','edit']],

            ['sex','required','on'=>['create','edit']],
            ['sex','in','range'=>[1,2,3],'on'=>['create','edit']],

            ['phone','required','on'=>['create','edit']],
            ['phone','match','pattern'=>'/^1[3-9]\d{9}$/','on'=>['create','edit']],

            ['other_phone','default'],

            ['company','required','on'=>['create','edit']],
            ['company','string', 'max' => 100,'on'=>['create','edit']],

            ['node_id','exist','on'=>['node'],'targetClass'=>Node::className(),'targetAttribute'=>['node_id'=>'id']],
            ['content','required','on'=>'node'],

            ['follow_at','safe','on'=>['remark']],
            ['next_follow_at','safe','on'=>['remark']],
            ['follow_user_id','safe','on'=>['remark']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => '客户姓名',
            'sex' => '客户性别',
            'phone' => '联系电话',
            'other_phone' => '其它电话',
            'company' => '公司名称',
            'node_id' => '节点',
            'follow_at' => '跟进时间',
            'next_follow_at' => '下次跟进时间',
            'created_user_id' => 'Created User ID',
            'follow_user_id' => '跟进用户ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'content' => '备注',
        ];
    }

    public function getSexText()
    {
        return ArrayHelper::getValue(self::$sex_info,$this->sex);
    }

    public function getNode()
    {
        return $this->hasOne(Node::className(),['id'=>'node_id']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(),['id'=>'created_user_id']);
    }

    public function updateNode()
    {
        if ($this->validate()){
            $db = Yii::$app->db;
            $transaction = $db->beginTransaction();
            try{
                $db->createCommand()->insert('project_node',[
                    'project_id' => Yii::$app->request->get('id'),
                    'old' => $this->getOldAttribute('node_id'),
                    'new' => $this->node_id,
                    'content' => $this->content,
                    'user_id' => Yii::$app->user->identity->id,
                    'created_at' => time(),
                    'updated_at' => time(),
                ])->execute();
                $this->save(false);
                $transaction->commit();
                return true;
            }catch (\Exception $exception){
                $transaction->rollBack();
                return false;
            }
        }
        return false;
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if ($insert){
            Yii::$app->db->createCommand()->insert('project_remark',[
                'project_id' => $this->id,
                'content' => '添加项目',
                'user_id' => Yii::$app->user->identity->id,
                'created_at' => time(),
                'updated_at' => time(),
            ])->execute();
        }
    }

    public function softDelete()
    {
        $this->deleted_at = time();
        $this->deleted_user_id = Yii::$app->user->identity->id;
        return $this->save();
    }


}
